package com.rfid.afd.model;

import com.google.gson.JsonObject;
import com.rfid.config.ConfigManager;
import com.rfid.config.Constant;
import com.rfid.db.bean.Gather;
import com.rfid.db.bean.Operation;
import com.rfid.db.bean.Rfid;
import com.rfid.db.bean.Shunjia;
import com.rfid.okhttp.ProgressRequestBody;
import com.rfid.rls_psw.App;
import com.rfid.util.DBManager;
import com.rfid.util.FileUtil;
import com.rfid.util.NetUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.ForwardingSink;
import retrofit2.http.PATCH;

public class SyncModel extends BaseModel{


    public int  generateGatherFile(String path) throws IOException {
        File file = new File(path);
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        List<Gather> gathers = DBManager.queryGathers();
        FileOutputStream fos = new FileOutputStream(path);
        for(Gather gather:gathers) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uid",gather.getUid());
            jsonObject.addProperty("barcode",gather.getBarcode());
            jsonObject.addProperty("title","");
            jsonObject.addProperty("bookindex","");
            jsonObject.addProperty("optime",gather.getOptime());
            jsonObject.addProperty("bookplace",gather.getShelf());
            jsonObject.addProperty("wkno",gather.getUser());
            jsonObject.addProperty("library",gather.getLibrary());
            fos.write((jsonObject.toString() + "\n").getBytes());
        }
        fos.close();
        return gathers.size();
    }

    public long getUnUploadItemCount() {
        return DBManager.queryUnUploadCount();
    }

    public int  generateLocateFile(String path) throws IOException {
        File file = new File(path);
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        List<Operation> operations = DBManager.queryUnuploadLocateOperation();
        FileOutputStream fos = new FileOutputStream(path);
        for(Operation operation:operations) {
            Rfid rfid = DBManager.queryRfidById(operation.getRfid());
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uid",rfid.getUid());
            jsonObject.addProperty("barcode",rfid.getBarcode());
            jsonObject.addProperty("title",rfid.getBookName());
            jsonObject.addProperty("optime",operation.getDate());
            jsonObject.addProperty("shelfcode",rfid.getShelf());
            jsonObject.addProperty("wkno",operation.getUser());
            jsonObject.addProperty("note","强制");
            fos.write((jsonObject.toString() + "\n").getBytes());
        }
        List<Shunjia> shunjias = DBManager.queryShunjias();
        for(Shunjia operation:shunjias) {
            Rfid rfid = DBManager.queryRfidByUid(operation.getEpc());
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uid",rfid.getUid());
            jsonObject.addProperty("barcode",rfid.getBarcode());
            jsonObject.addProperty("title",rfid.getBookName());
            jsonObject.addProperty("optime",operation.getDate());
            jsonObject.addProperty("shelfcode",rfid.getShelf());
            jsonObject.addProperty("wkno",operation.getUser());
            jsonObject.addProperty("note","首书");
            fos.write((jsonObject.toString() + "\n").getBytes());
        }
        fos.close();
        return operations.size() + shunjias.size();
    }

    public int  generateCheckFile(String path) throws IOException {
        File file = new File(path);
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        List<Operation> operations = DBManager.queryUnuploadCheckOperation();
        FileOutputStream fos = new FileOutputStream(path);
        for(Operation operation:operations) {
            Rfid rfid = DBManager.queryRfidById(operation.getRfid());
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uid",rfid.getUid());
            jsonObject.addProperty("barcode",rfid.getBarcode());
            jsonObject.addProperty("title",rfid.getBookName());
            jsonObject.addProperty("optime",operation.getDate());
            jsonObject.addProperty("shelfcode",rfid.getShelf());
            jsonObject.addProperty("wkno",operation.getUser());
            fos.write((jsonObject.toString() + "\n").getBytes());
        }
        fos.close();
        return operations.size();
    }
    public int  generateDeleteFile(String path) throws IOException {
        File file = new File(path);
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        List<Operation> operations = DBManager.queryUnuploadDeleteOperation();
        FileOutputStream fos = new FileOutputStream(path);
        for(Operation operation:operations) {
            Rfid rfid = DBManager.queryRfidById(operation.getRfid());
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uid",rfid.getUid());
            jsonObject.addProperty("barcode",rfid.getBarcode());
            jsonObject.addProperty("title",rfid.getBookName());
            jsonObject.addProperty("optime",operation.getDate());
            jsonObject.addProperty("wkno",operation.getUser());
            fos.write((jsonObject.toString() + "\n").getBytes());
        }
        fos.close();
        return operations.size();
    }
    public int  generateShangjiaFile(String path) throws IOException {
        File file = new File(path);
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        List<Operation> operations = DBManager.queryUnuploadShangjiaOperation();
        FileOutputStream fos = new FileOutputStream(path);
        for(Operation operation:operations) {
            Rfid rfid = DBManager.queryRfidById(operation.getRfid());
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uid",rfid.getUid());
            jsonObject.addProperty("barcode",rfid.getBarcode());
            jsonObject.addProperty("title",rfid.getBookName());
            jsonObject.addProperty("optime",operation.getDate());
            jsonObject.addProperty("shelfcode",rfid.getShelf());
            jsonObject.addProperty("wkno",operation.getUser());
            fos.write((jsonObject.toString() + "\n").getBytes());
        }
        fos.close();
        return operations.size();
    }

    public void markUploaded(int type) {
        List<Operation> operations = DBManager.queryUnuploadOperation(type);
        if(operations.size() == 0) {
            return;
        }
        for(Operation operation : operations) {
            operation.setUpload(1);
        }
        DBManager.updateOperate(operations);
    }

    //服务端定义 0:上架 1:下架  2:定位 3:盘点 4:阅览 5:采集 6:剔除
    private String makeLine(Operation operation, Rfid rfid,String op) {
        StringBuffer sb = new StringBuffer();
        sb.append(rfid.getUid());
        sb.append(",");
        sb.append(rfid.getBarcode());
        sb.append(",");
        sb.append(rfid.getShelf());
        sb.append(",");
        sb.append(operation.getUser());
        sb.append(",");
        sb.append(operation.getDate());
        sb.append(",");//操作设备留空
        sb.append(",");
        sb.append(rfid.getSite());
        sb.append(",");
        sb.append(op);
        sb.append("\n");
        return sb.toString();
    }

    public int createShunjiaFile(String path) throws IOException {
        List<Shunjia> shunjias = DBManager.queryShunjias();
        if(shunjias.size() == 0) {
            return 0;
        }
        FileOutputStream fos = new FileOutputStream(path);
        for(Shunjia shunjia : shunjias) {
            StringBuffer sb = new StringBuffer();
            sb.append(shunjia.getEpc());
            sb.append(",");
            sb.append(shunjia.getShelf());
            sb.append(",");
            sb.append(shunjia.getShelfName());
            sb.append(",");
            sb.append(shunjia.getStartIndex());
            sb.append(",");
            sb.append(shunjia.getEndIndex());
            sb.append(",");
            sb.append(shunjia.getUser());
            sb.append(",");
            sb.append(shunjia.getDate());
            sb.append(",");
            sb.append(shunjia.getSite());
            sb.append("\n");
            fos.write(sb.toString().getBytes());
        }
        fos.flush();
        fos.close();
        return shunjias.size();
    }

    public  void upLoadFile(String filePath) throws IOException {
        ForwardingSink sinl;
        OkHttpClient httpClient = new OkHttpClient();
        String requestUrl = ConfigManager.getInstance().getConfig().getBaseUrl() + "/upload/upload";
        //创建File
        File file = new File(filePath);
        //创建RequestBody
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        new ProgressRequestBody(RequestBody.create(MediaType.parse("*/*"), new File(filePath)),mListener))
                .build();
        //创建Request
        final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
        final Call call = httpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
            Response response = call.execute();
            System.out.println(response.body().string());
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                System.out.println("上传失败");
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    String string = response.body().string();
//                    System.out.println(string);
//                } else {
//                }
//            }
//        });
    }

    public void downloadDBFile(String path) throws IOException {
        NetUtil.downloadFile(ConfigManager.getInstance().getConfig().getBaseUrl() + "/download/download?filename=rfid.db",path);
    }

    private ProgressRequestBody.ProgressListener mListener = new ProgressRequestBody.ProgressListener() {
        @Override
        public void onProgress(long write, long total) {
            System.out.println("onProgress write = " + write + ",total = " + total);
            if(total == 0) {
                return;
            }
            Float ratio = write/(float)total*100;
            App.getInstance().getObservable().notifyObservers(ratio);
        }
    };

}
